import 'package:shared_preferences/shared_preferences.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';

class PreferencesService extends GetxService {
  SharedPreferences? _prefs;

  SharedPreferences get prefs {
    if (_prefs == null) {
      throw Exception('SharedPreferences not initialized. Call init() first.');
    }
    return _prefs!;
  }

  @override
  Future<void> onInit() async {
    super.onInit();
    await init();
  }

  Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  // 主题相关
  static const String _themeKey = 'theme_mode';
  
  ThemeMode getThemeMode() {
    final themeIndex = prefs.getInt(_themeKey) ?? 0;
    return ThemeMode.values[themeIndex];
  }

  Future<void> setThemeMode(ThemeMode themeMode) async {
    await prefs.setInt(_themeKey, themeMode.index);
  }

  // 语言相关
  static const String _languageKey = 'language';
  
  Locale? getLanguage() {
    final languageCode = prefs.getString(_languageKey);
    if (languageCode == null) return null;
    
    final parts = languageCode.split('_');
    if (parts.length == 2) {
      return Locale(parts[0], parts[1]);
    }
    return Locale(parts[0]);
  }

  Future<void> setLanguage(Locale locale) async {
    final languageCode = locale.countryCode != null 
        ? '${locale.languageCode}_${locale.countryCode}'
        : locale.languageCode;
    await prefs.setString(_languageKey, languageCode);
  }

  // 天翼云设置
  static const String _autoSyncKey = 'auto_sync';
  static const String _syncIntervalKey = 'sync_interval';
  static const String _maxUploadConcurrentKey = 'max_upload_concurrent';
  static const String _maxDownloadConcurrentKey = 'max_download_concurrent';
  static const String _chunkSizeKey = 'chunk_size';
  
  bool getAutoSync() {
    return prefs.getBool(_autoSyncKey) ?? true;
  }

  Future<void> setAutoSync(bool autoSync) async {
    await prefs.setBool(_autoSyncKey, autoSync);
  }

  int getSyncInterval() {
    return prefs.getInt(_syncIntervalKey) ?? 30; // 默认30分钟
  }

  Future<void> setSyncInterval(int minutes) async {
    await prefs.setInt(_syncIntervalKey, minutes);
  }

  int getMaxUploadConcurrent() {
    return prefs.getInt(_maxUploadConcurrentKey) ?? 3;
  }

  Future<void> setMaxUploadConcurrent(int count) async {
    await prefs.setInt(_maxUploadConcurrentKey, count);
  }

  int getMaxDownloadConcurrent() {
    return prefs.getInt(_maxDownloadConcurrentKey) ?? 3;
  }

  Future<void> setMaxDownloadConcurrent(int count) async {
    await prefs.setInt(_maxDownloadConcurrentKey, count);
  }

  int getChunkSize() {
    return prefs.getInt(_chunkSizeKey) ?? 1024 * 1024; // 默认1MB
  }

  Future<void> setChunkSize(int size) async {
    await prefs.setInt(_chunkSizeKey, size);
  }

  // 文件管理设置
  static const String _defaultDownloadPathKey = 'default_download_path';
  static const String _showHiddenFilesKey = 'show_hidden_files';
  static const String _sortTypeKey = 'sort_type';
  static const String _sortOrderKey = 'sort_order';
  static const String _gridViewKey = 'grid_view';
  
  String? getDefaultDownloadPath() {
    return prefs.getString(_defaultDownloadPathKey);
  }

  Future<void> setDefaultDownloadPath(String path) async {
    await prefs.setString(_defaultDownloadPathKey, path);
  }

  bool getShowHiddenFiles() {
    return prefs.getBool(_showHiddenFilesKey) ?? false;
  }

  Future<void> setShowHiddenFiles(bool show) async {
    await prefs.setBool(_showHiddenFilesKey, show);
  }

  String getSortType() {
    return prefs.getString(_sortTypeKey) ?? 'name'; // name, size, date, type
  }

  Future<void> setSortType(String sortType) async {
    await prefs.setString(_sortTypeKey, sortType);
  }

  bool getSortOrder() {
    return prefs.getBool(_sortOrderKey) ?? true; // true: ascending, false: descending
  }

  Future<void> setSortOrder(bool ascending) async {
    await prefs.setBool(_sortOrderKey, ascending);
  }

  bool getGridView() {
    return prefs.getBool(_gridViewKey) ?? false;
  }

  Future<void> setGridView(bool gridView) async {
    await prefs.setBool(_gridViewKey, gridView);
  }

  // 通知设置
  static const String _uploadNotificationKey = 'upload_notification';
  static const String _downloadNotificationKey = 'download_notification';
  static const String _syncNotificationKey = 'sync_notification';
  
  bool getUploadNotification() {
    return prefs.getBool(_uploadNotificationKey) ?? true;
  }

  Future<void> setUploadNotification(bool enabled) async {
    await prefs.setBool(_uploadNotificationKey, enabled);
  }

  bool getDownloadNotification() {
    return prefs.getBool(_downloadNotificationKey) ?? true;
  }

  Future<void> setDownloadNotification(bool enabled) async {
    await prefs.setBool(_downloadNotificationKey, enabled);
  }

  bool getSyncNotification() {
    return prefs.getBool(_syncNotificationKey) ?? true;
  }

  Future<void> setSyncNotification(bool enabled) async {
    await prefs.setBool(_syncNotificationKey, enabled);
  }

  // 缓存设置
  static const String _maxCacheSizeKey = 'max_cache_size';
  static const String _autoClearCacheKey = 'auto_clear_cache';
  
  int getMaxCacheSize() {
    return prefs.getInt(_maxCacheSizeKey) ?? 500; // 默认500MB
  }

  Future<void> setMaxCacheSize(int sizeMB) async {
    await prefs.setInt(_maxCacheSizeKey, sizeMB);
  }

  bool getAutoClearCache() {
    return prefs.getBool(_autoClearCacheKey) ?? true;
  }

  Future<void> setAutoClearCache(bool enabled) async {
    await prefs.setBool(_autoClearCacheKey, enabled);
  }

  // 安全设置
  static const String _biometricAuthKey = 'biometric_auth';
  static const String _autoLockKey = 'auto_lock';
  static const String _lockTimeoutKey = 'lock_timeout';
  
  bool getBiometricAuth() {
    return prefs.getBool(_biometricAuthKey) ?? false;
  }

  Future<void> setBiometricAuth(bool enabled) async {
    await prefs.setBool(_biometricAuthKey, enabled);
  }

  bool getAutoLock() {
    return prefs.getBool(_autoLockKey) ?? false;
  }

  Future<void> setAutoLock(bool enabled) async {
    await prefs.setBool(_autoLockKey, enabled);
  }

  int getLockTimeout() {
    return prefs.getInt(_lockTimeoutKey) ?? 5; // 默认5分钟
  }

  Future<void> setLockTimeout(int minutes) async {
    await prefs.setInt(_lockTimeoutKey, minutes);
  }

  // 清除所有设置
  Future<void> clearAll() async {
    await prefs.clear();
  }

  // 导出设置
  Map<String, dynamic> exportSettings() {
    final keys = prefs.getKeys();
    final settings = <String, dynamic>{};
    
    for (final key in keys) {
      final value = prefs.get(key);
      if (value != null) {
        settings[key] = value;
      }
    }
    
    return settings;
  }

  // 导入设置
  Future<void> importSettings(Map<String, dynamic> settings) async {
    for (final entry in settings.entries) {
      final key = entry.key;
      final value = entry.value;
      
      if (value is bool) {
        await prefs.setBool(key, value);
      } else if (value is int) {
        await prefs.setInt(key, value);
      } else if (value is double) {
        await prefs.setDouble(key, value);
      } else if (value is String) {
        await prefs.setString(key, value);
      } else if (value is List<String>) {
        await prefs.setStringList(key, value);
      }
    }
  }
}